package com.chen.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    static {
        Properties properties = new Properties();
        InputStream in = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        try{
            properties.load(in);
        }catch (IOException e){
            e.printStackTrace();
        }
        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }
    public static Connection getConnection(){
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    public static ResultSet execute(Connection connection,PreparedStatement ps,ResultSet resultSet,String sql,Object[] params) throws SQLException {
        ps = connection.prepareStatement(sql);
        for (int i=0;i<params.length;i++){
            //setObject占位符下标从1开始，我们数组是从0开始
            ps.setObject(i+1,params[i]);
        }
        resultSet=ps.executeQuery();
        return resultSet;
    }
    public static int execute(Connection connection,PreparedStatement ps,String sql,Object[] params) throws SQLException {
        ps=connection.prepareStatement(sql);
        for (int i=0;i<params.length;i++){
            //setObject占位符下标从1开始，我们数组是从0开始
            ps.setObject(i+1,params[i]);
        }
        int updateRows=ps.executeUpdate();
        return updateRows;
    }
    public static boolean closeResource(Connection connection,PreparedStatement ps,ResultSet resultSet){
        boolean closeFlag=true;
        if (resultSet!=null){
            try {
                resultSet.close();
                //GC回收
                resultSet=null;
            } catch (SQLException e) {
                e.printStackTrace();
                closeFlag=false;
            }
        }
        if (ps!=null){
            try {
                ps.close();
                ps=null;
            } catch (SQLException e) {
                e.printStackTrace();
                closeFlag=false;
            }
        }
        if (connection!=null){
            try {
                connection.close();
                connection=null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return closeFlag;
    }
}
